package com.ikangtai.shecare.personal;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.CollectedArticle;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.baseView.collectionList.CollectionAdapter;
import com.ikangtai.shecare.common.baseView.collectionList.CollectionBean;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.DelCollectedArticle;
import com.ikangtai.shecare.common.swipemenulistview.SwipeMenu;
import com.ikangtai.shecare.common.swipemenulistview.SwipeMenuCreator;
import com.ikangtai.shecare.common.swipemenulistview.SwipeMenuItem;
import com.ikangtai.shecare.common.swipemenulistview.SwipeMenuListView;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.FileUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.knowledge.ArticleActivity;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.util.List;

public class CollectionActivity extends BaseActivity implements AdapterView.OnCreateContextMenuListener {

    private TopBar topBar;
    private SwipeMenuListView collectionListView;
    private DateUtil dateUtil = new DateUtil();
    private List<CollectionBean> collectionBeanList = null;
    private CollectedArticle collectedArticle = new CollectedArticle();
    private CollectionBean collectionBean = new CollectionBean();
    private BaseAdapter collectionAdapter;
    private static final int RESP_OK = 1;
    private static final int RESP_NOK = 2;
    private DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_personal_collection);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        collectionListView = (SwipeMenuListView) findViewById(R.id.collectionListView);
        showCollectionListFromCache();
        //collectionListView.setOnItemLongClickListener(this);
//        collectionListView.setOnCreateContextMenuListener(this);
    }

    private void showCollectionListFromCache() {
        collectionBeanList = getCollectionBeanListFromCache();
        realShowCollectionList();
    }

    private void realShowCollectionList() {
        collectionAdapter = new CollectionAdapter(this, collectionBeanList);
        Log.d("aaaaaaaaa", "初次进入的加载收藏list"+JSON.toJSONString(collectionBeanList));
        collectionListView.setAdapter(collectionAdapter);
        setListViewHeight();
        swipeMenuManager();
    }

    /**
     * 左划删除
     */
    private void swipeMenuManager() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(CollectionActivity.this);
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                deleteItem.setWidth(dp2px(90));
                deleteItem.setTitle(getString(R.string.record_ovulation_photo_delete));
                deleteItem.setTitleSize(18);
                deleteItem.setTitleColor(Color.WHITE);
//                deleteItem.setIcon(R.drawable.ic_delete);
                menu.addMenuItem(deleteItem);
            }
        };

        collectionListView.setMenuCreator(creator);
        collectionListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        String articleTitle = collectionBeanList.get(position).getCollectionTitle();
                        String articleId = String.valueOf(collectionBeanList.get(position).getArticleId());
                        String collectionID = App.articleId2CollectionIDMap.get(articleId);

                        CollectionBean collectionBean = collectionBeanList.remove(position);
                        Log.d("aaaaaaaaa", "删除一项收藏的list"+JSON.toJSONString(collectionBeanList));
                        collectionAdapter.notifyDataSetChanged();

                        //HomeFragment对应的推荐文章列表里若有此收藏文章，则更新其收藏状态
                        DelCollectedArticle delCollectedArticle = new DelCollectedArticle(collectionBean.getArticleId());
                        EventBus.getDefault().post(delCollectedArticle);

                        removeCollectedArticleFromNetwork(collectionID, articleId, articleTitle);

                        break;
                }
            }
        });

        collectionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String articleId = String.valueOf(collectionBeanList.get(position).getArticleId());
                Intent intent = new Intent(CollectionActivity.this, ArticleActivity.class);
                intent.putExtra("articleId", App.status + "_" + articleId);

                AppLog.i("Adapter articleId = " + articleId);
                CollectionActivity.this.startActivity(intent);
            }
        });

    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private List<CollectionBean> getCollectionBeanListFromCache() {
        AppLog.i("getCollectionBeanListFromCache!");

        dbManager = new DBManager(getApplicationContext());
        List<CollectionBean> collectionBeanList = dbManager.getCollectionArticles(App.userName);

        return collectionBeanList;
    }

    private void setListViewHeight() {
        if (collectionBeanList == null)
            return;

        int totalHeight = 0;

        for (int i = 0; i < collectionBeanList.size(); i++) {
            View listItem = collectionAdapter.getView(i, null, collectionListView);

            //给listItem初始化宽高，否则会报空
            ViewGroup.LayoutParams layoutParams = listItem.getLayoutParams();
            if (layoutParams == null) {
                layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                listItem.setLayoutParams(layoutParams);
            }

            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = collectionListView.getLayoutParams();
        params.height = totalHeight + (collectionListView.getDividerHeight() * (collectionListView.getCount() - 1));
        collectionListView.setLayoutParams(params);
    }


//    @Override
//    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//        Toast.makeText(getApplicationContext(),"postion="+position+",id="+id,Toast.LENGTH_LONG).show();
//        return true;
//    }


    // menu.add(groupId, itemId, order, title)
    // groupld 这个菜单的组别
    // itemid 是用来获取这个指定菜单项的
    // 所谓order就是这个组别的第几项，0为第一项
    // title 不用说都知道是显示的标题了
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(0, 0, 0, R.string.delete_collect);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        TextView articleTitleTextView = (TextView) menuInfo.targetView.findViewById(R.id.articleTitleTextView);
        String articleTitle = articleTitleTextView.getText().toString();
        String articleId = (String) articleTitleTextView.getTag();
        String collectionID = App.articleId2CollectionIDMap.get(articleId);

        AppLog.i("delete menuInfo.position = " + menuInfo.position + "deleted collectionBean = " + collectionBean.getArticleId());
        CollectionBean collectionBean = collectionBeanList.remove(menuInfo.position);
        collectionAdapter.notifyDataSetChanged();

        //HomeFragment对应的推荐文章列表里若有此收藏文章，则更新其收藏状态
        DelCollectedArticle delCollectedArticle = new DelCollectedArticle(collectionBean.getArticleId());
        EventBus.getDefault().post(delCollectedArticle);

        removeCollectedArticleFromNetwork(collectionID, articleId, articleTitle);
        return super.onContextItemSelected(item);
    }

    public void removeCollectedArticleFromNetwork(final String collectionID, final String articleId, final String articleTitle) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "collection/addCollection.json";
        try {
            JSONArray collectionBeanJsonArray = new JSONArray();
            JSONObject collectionBeanJSONObject = new JSONObject();

            collectionBeanJSONObject.put("collectionID", collectionID);
            collectionBeanJSONObject.put("collectionName", articleTitle);
            collectionBeanJSONObject.put("collectionURL", articleId);
            collectionBeanJSONObject.put("collectionFrom", 1);
            collectionBeanJSONObject.put("collectionDate", dateUtil.getDate());
            collectionBeanJSONObject.put("collectionDelete", 1);
            collectionBeanJsonArray.put(collectionBeanJSONObject);

            collectedArticle.collectionID = collectionID;
            collectedArticle.collectionName = articleTitle;
            collectedArticle.collectionURL = articleId;
            collectedArticle.collectionFrom = 1;
            collectedArticle.collectionDate = dateUtil.getDate();
            collectedArticle.collectionDelete = 1;

            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("collections", collectionBeanJsonArray);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    collectionBean.setRespCode(RESP_NOK);
                    collectionBean.setArticleId(Integer.valueOf(articleId));
                    sendNOKResp(collectionBean);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        if (App.HTTP_RESP_OK == respCode) {
                            collectionBean.setRespCode(RESP_OK);
                            collectionBean.setArticleId(Integer.valueOf(articleId));
                            sendOKResp(collectionBean);
                            AppLog.i("removeCollectedArticleFromNetwork onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            removeCollectedArticleFromNetwork(collectionID, articleId, articleTitle);
                        } else {
                            collectionBean.setRespCode(RESP_NOK);
                            collectionBean.setArticleId(Integer.valueOf(articleId));
                            sendNOKResp(collectionBean);
                            AppLog.i("removeCollectedArticleFromNetwork onResponse failed! respCode is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("removeCollectedArticleFromNetwork JSONException!");
                        e.printStackTrace();

                        collectionBean.setRespCode(RESP_NOK);
                        collectionBean.setArticleId(Integer.valueOf(articleId));
                        sendNOKResp(collectionBean);
                    }
                }

                private void sendNOKResp(CollectionBean collectionBean) {
                    EventBus.getDefault().post(collectionBean);
                }

                private void sendOKResp(CollectionBean collectionBean) {
                    EventBus.getDefault().post(collectionBean);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Subcriber
    private void removeCollectedArticle(CollectionBean collectionBean) {
        switch (collectionBean.getRespCode()) {
            case RESP_OK:
                //在本地sqlite数据库删除对应的收藏行
                AppLog.i("removeCollectedArticle data in local sqlite database, and DB_SYNCED!");
                dbManager.addOrDelete(collectedArticle, App.DB_SYNCED);
                //保存收藏的文章图片到本地，或者删除取消收藏的本地图片
                deleteCollectedImageFromCache(collectionBean);
                break;
            case RESP_NOK:
                //网络请求失败，仍然添加到本地sqlite数据库
                AppLog.i("removeCollectedArticle data in local sqlite database, but DB_NOT_SYNCED!");
                dbManager.addOrDelete(collectedArticle, App.DB_NOT_SYNCED);
                deleteCollectedImageFromCache(collectionBean);
                break;
        }

        setPrefArticleCollection(collectionBean);
    }

    private void deleteCollectedImageFromCache(CollectionBean collectionBean) {
        String fileName = "collectedArticle" + collectionBean.getArticleId() + ".jpg";
        String externalCacheDir = getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/";
        String collectedImagePath = externalCacheDir + fileName;
        AppLog.i("deleteCollectedImageFromCache, fileName = " + fileName);

        FileUtil.deleteFile(collectedImagePath);
    }

    private void setPrefArticleCollection(CollectionBean collectionBean){
        int articleId = collectionBean.getArticleId();

        if (App.getPreferenceInt("article0_id") == articleId)
            App.savePreference("article0_isCollected", false);
        else if (App.getPreferenceInt("article1_id") == articleId)
            App.savePreference("article1_isCollected", false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}
